const mongoose = require("mongoose");
const Score = require("../models/scoreModel");

//创建成绩记录
exports.createScore = async (req, res) => {
  try {
    const newScore = await Score.create(req.body);
    // 201 Created 已创建
    res.status(201).json({
      status: "success",
      data: newScore,
    });
  } catch (err) {
    console.log("创建成绩记录失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//获取所有成绩记录（审核员）
exports.getAllScore = async (req, res) => {
  try {
    const scoreList = await Score.find()
      .populate({ path: "userId", select: "name group" })
      .populate({ path: "testId", select: "title" });
    res.status(200).json({
      status: "success",
      data: scoreList,
    });
  } catch (err) {
    console.log("获取所有成绩记录失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//获取指定分组的所有成绩（管理员）
exports.getScoreByGroup = async (req, res) => {
  try {
    const scoreList = await Score.find()
      .populate({ path: "userId", select: "name group" })
      .populate({ path: "testId", select: "title" });

    const newScoreList = scoreList.filter((item) => {
      return item.userId.group === req.user.group;
    });

    res.status(200).json({
      status: "success",
      data: newScoreList,
    });
  } catch (error) {
    console.log("获取指定分组的成绩记录失败", error),
      res.status(404).json({
        Error: error,
      });
  }
};

//获取指定试卷的所有成绩
exports.getScoreByTestId = async (req, res) => {
  try {
    const testId = mongoose.Types.ObjectId(req.params.testId);
    const Data = await Score.find({ testId: testId });
    res.status(200).json({
      status: "success",
      data: Data,
    });
  } catch (error) {
    console.log("获取指定试卷的所有成绩失败", error),
      res.status(404).json({
        Error: error,
      });
  }
};
